package com.melodyframe.common.tools.convert;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.lang.StringUtils;

public class StringConverter extends AbstractConverter<String> {
	@Override
	public Class<?>[] getSupports() {
		return new Class<?>[] { String.class };
	}

	@Override
	public String convert(Object object, Class<?> classType, String format) {
		if (null == object) {
			return null;
		} else if (object instanceof String) {
			return (String) object;
		} else if (object instanceof Date) {
			SimpleDateFormat dateFormat = new SimpleDateFormat(
					null == format ? "yyyy-MM-dd HH:mm:ss" : format);
			return dateFormat.format((Date) object);
		} else if (object instanceof Object[]) {
			Object[] array = (Object[]) object;
			return convertFromArray(array, classType, format);
		} else {
			return object.toString();
		}
	}

	private String convertFromArray(Object[] array, Class<?> classType,
			String format) {
		if (array.length > 1) {
			String[] stringArray = new String[array.length];
			for (int i = 0; i < array.length; i++) {
				stringArray[i] = this.convert(array[i], classType, format);
			}
			if (null != format) {
				return StringUtils.join(stringArray, format);
			} else {
				return StringUtils.join(stringArray);
			}
		} else if (array.length == 1) {
			return this.convert(array[0], classType, format);
		} else {
			return null;
		}
	}
}
